package com.eat.service.impl;

import com.eat.constant.UserConstant;
import com.eat.dao.UserDao;
import com.eat.dao.impl.UserDaoImpl;
import com.eat.domain.User;
import com.eat.exception.CheckException;
import com.eat.service.UserService;
import com.eat.utils.CheckUtils;
import com.eat.utils.StringUtils;

import java.util.List;

/**
 * Created by ZH on 2018/4/17.
 */
public class UserServiceImpl implements UserService {
    private UserDao udi = new UserDaoImpl();

    @Override
    public User login(String accountName, String password) {
        CheckUtils.check(StringUtils.isNotEmpty(accountName), "登录时帐户不能为空");
        CheckUtils.check(StringUtils.isNotEmpty(password), "登录时密码不能为空");
        int count = udi.count(accountName, password);
        if (count > 0) {
            return udi.findByAccountName(accountName);
        } else {
            return null;
        }
    }

    @Override
    public int normalUserRegister(User user) {
        return register(user, UserConstant.NORMAL_USER);
    }

    @Override
    public int shopUserRegister(User user) {
        return register(user, UserConstant.SHOP_USER);
    }

    @Override
    public int adminUserRegister(User user) {
        return register(user, UserConstant.ADMIN_USER);
    }

    private int register(User user, int type) {
        CheckUtils.check(StringUtils.isNotEmpty(user.getAccountName()), "用户名不能为空");
        CheckUtils.check(StringUtils.isNotEmpty(user.getPassword()), "密码不能为空");
        CheckUtils.check(StringUtils.isNotEmpty(user.getUserAddress()), "收货地址不能为空");
        CheckUtils.check(StringUtils.isNotEmpty(user.getUserPhone()), "联系方式不能为空");
        // 判断用户名是否已经存在
        int count = udi.count1(user.getAccountName());
        if (count > 0) {
            throw new CheckException("用户名已经存在");
        }
        user.setType(type);
        return udi.insert(user);
    }

    @Override
    public void logOut(Long userId) {
        User user = udi.findOne(userId);
        CheckUtils.check(user != null, "不存在该用户");
        System.out.println(user.getUserName() + " 帐户已经退出");
    }

    @Override
    public int deleteByUserId(long userId) {
        return udi.delete(userId);
    }

    @Override
    public boolean isNormalUser(User user) {
        return user.getType() == UserConstant.NORMAL_USER;
    }

    @Override
    public boolean isShopUser(User user) {
        return user.getType() == UserConstant.SHOP_USER;
    }

    @Override
    public boolean isAdminUser(User user) {
        return user.getType() == UserConstant.ADMIN_USER;
    }

    @Override
    public List<User> findAll() {
        return udi.findAll();
    }
}
